package com.glory.brepda.activity.mfg;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.entity.LotAndPackagingfileEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import butterknife.BindView;
import butterknife.OnClick;

public class BreLanjianPasteBarCodeWGOutPutActivity  extends BaseActivity {

    @BindView(R.id.tvBCOPType)
    TextView tvBCOPType;
    @BindView(R.id.ivBCOPArrow)
    ImageView ivBCOPArrow;
    @BindView(R.id.flBCOPList)
    FrameLayout flBCOPList;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etLotID)
    FreeUI_ClearEditText etLotID;
    @BindView(R.id.xinghao)
    EditText xinghao;
    @BindView(R.id.fengzuang)
    EditText fengzuang;
//    @BindView(R.id.spinner1)
//    Spinner spinner1;
    @BindView(R.id.man)
    EditText man;
    @BindView(R.id.custcode)
    EditText custcode;
    @BindView(R.id.shuliang)
    EditText shuliang;
    @BindView(R.id.base_reel_num)
    EditText base_reel_num;
    @BindView(R.id.base_box_num)
    EditText base_box_num;
    @BindView(R.id.reel_num)
    EditText reel_num;
    @BindView(R.id.box_num)
    EditText box_num;
    @BindView(R.id.bar_code_num)
    EditText bar_code_num;
    @BindView(R.id.avg_num)
    EditText avg_num;
    @BindView(R.id.computer)
    Button computer;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;

    private String WO_ID;
    private int MAIN_QTY=0;
    private int MAN_NUM=0;
//    private String TYPE;
    private int BASE_REEL_NUM=0;
    private int BASE_BOX_NUM=0;
    private int REEL_NUM=0;
    private int BOX_NUM=0;
    private int BAR_CODE_NUM=0;
    private double AVG_NUM=0;
    String showMans = "";

    private FreeUI_GeneralPop codePop;
//    String[] city=new String[]{"贴标签","贴标签+吹贴标签"};
    private ArrayList<String> city = new ArrayList<>(Arrays.asList("贴标签","贴标签+吹贴标签"));
    private LotAndPackagingfileEntity entity;
//    private BreLanjianPasteBarCodeWGOutPutActivity.MTextWatcher man1;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_bre_lanjian_paste_bar_code_wgout_put;
    }

    @Override
    protected void initView() {

        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        initEdit(etLotID, sa -> {
            //获取lot信息
//            LotUtils.searchLotInfo(getApplicationContext(), sa, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
//                @Override
//                public void onSuccess(LotInfoEntity body) {
//                    lotInfoEntity = body;
//                    if(body.getLOT() != null || !body.getLOT().equals("null") ){
//                        fengzuang.setText(body.getLOT().getMAINMATTYPE());
//                        shuliang.setText(body.getLOT().getMAINQTY());
//                        if(body.getLOT().getPROCEDURENAME() != null){
//                            xinghao.setText(body.getLOT().getUDF().getProductModel());
//                        }else{
//                            Toast.makeText(getApplicationContext(), "该批次型号为空", Toast.LENGTH_SHORT).show();
//                        }
//                        if(body.getLOT().getLOCATION() != null){
//                            shebei.setText(body.getLOT().getLOCATION());
//                        }else{
//                            Toast.makeText(getApplicationContext(), "该批次设备为空", Toast.LENGTH_SHORT).show();
//                        }
////                                扫描带出的数据
//                        WO_ID=body.getLOT().getWOID();
//                        MAIN_QTY=Integer.parseInt(body.getLOT().getMAINQTY());
//                        CUSTOMER_CODE=body.getLOT().getCUSTOMERCODE();
//                        STEP_DESC=body.getLOT().getSTEPDESC();
//                        STEP_NAME=body.getLOT().getSTEPNAME();
////                                LOCATION=body.getLOT().getLOCATION();
//                    }
//                }
//                @Override
//                public void onFail(Throwable t) {
//
//                }
//            });
            FreeUI_EntityCallBack<BaseResponseBean<LotAndPackagingfileEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<LotAndPackagingfileEntity>>
                    (new TypeToken<BaseResponseBean<LotAndPackagingfileEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<LotAndPackagingfileEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                        entity = response.body().getResponse().getBody();
                        inputvalue(entity);
                        showToast("成功", true);
                        etLotID.requestFocus();
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<LotAndPackagingfileEntity>> response) {
                    super.onError(response);
                    loadError(response.getException(), "失败");
                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("LOT_ID", getText(etLotID));
            map.addProperty("ACTION_TYPE", "QUERY");
            NetUtils.requestPostNet("IF.PDA_QUERY_LOT_PACKS", "Common", getApplication(), map, callBack);
        });

        flBCOPList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (codePop != null) {
                    if (codePop.isShowing()) {
                        codePop.dismiss();
                    }
                } else {
                    codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flBCOPList.getWidth(), city, ivBCOPArrow, (ty, i) -> {
                        tvBCOPType.setText(ty);
                        Toast.makeText(getApplicationContext(),ty,Toast.LENGTH_SHORT).show();
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivBCOPArrow);
                codePop.showAsDropDown(flBCOPList, 0, 0);
            }
        });

    }


    @Override
    protected void initData() {
//        lot_id.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                if(lot_id.getText().toString().trim() == null || "".equals(lot_id.getText().toString().trim())){
//                    showToast("请先扫描批次信息", false);
//                    return false;
//                }
//                if(actionId== EditorInfo.IME_ACTION_SEARCH) {
////                    System.out.println("这里是监听扫码枪的回车事件");
//                    search();
//                    return true;
//                }
//                if(event.getKeyCode()==KeyEvent.KEYCODE_ENTER&&v.getText()!=null&& event.getAction() == KeyEvent.ACTION_DOWN){
////                    System.out.println("这里是监听手机的回车事件");
//                }
//                return true;
//            }
//        });

        //第一个参数表示在哪个Activity上显示，第二个参数是系统下拉框的样式，第三个参数是数组。
//        ArrayAdapter<String> adapter= new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item,city);//建立Adapter并且绑定数据源
//        spinner1.setAdapter(adapter);
//        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                String text= spinner1.getItemAtPosition(i).toString();
//                TYPE=text;
//                Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> adapterView) {
//            }
//        });
    }

    @OnClick({R.id.tvBaseSubmit,R.id.computer})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                submit();
                break;
            case R.id.computer:
                computers();
                break;
        }
    }

    private void computers(){
        if(getText(man).equals("")){
            showToast("请先输入员工姓名!", false);
            return;
        }
        showMans = man.getText().toString().trim();
        int len = showMans.length();
        String regex = "^[\u4e00-\u9fa5，]+";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(showMans);
        if(!matcher.matches()){
            showToast("字判断有误，只能包含中文或逗号，", false);
            return;
        }
        int sizeMan = 0;
        if(len>=4){   // 大于等于2人
            if(!showMans.contains("，")){
                FreeUI_GeneralFragmentDialog tipDialog = FreeApi_DialogUtils.getConfirmDialog(MyApp.app, "确定", "大于两人清把名字用“，”进行分割!", () -> {
                });
                tipDialog.show(getSupportFragmentManager(),"DIALOG");
                return;
            }
            // 如果最后一位或者第一位是逗号情况
            char[] aa = showMans.toCharArray();
            if(aa[0] == '，' || aa[aa.length-1]=='，'){
                showToast("姓名首位或者末尾位不能是逗号", false);
                return;
            }
            String[] manss = showMans.split("，");
            sizeMan=manss.length;
            String first = manss[0];

            if(sizeMan>1){
                boolean iscf = hasDuplicate(manss);
                if(iscf){
                    showToast("姓名存在重复！", false);
                    return;
                }
            }
            if(sizeMan>1){
                for (String item:manss
                     ) {
                    if(item.equals("")){
                        showToast("姓名存在空值！", false);
                        return;
                    }
                }
            }
            if(sizeMan>5){
                showToast("姓名数量不能超过5人！！", false);
                return;
            }

        }else{  // 一人
            sizeMan=1;
        }
        MAN_NUM = sizeMan;
        bar_code_num.setText(String.valueOf(BAR_CODE_NUM));
        AVG_NUM = BAR_CODE_NUM*1.0 / sizeMan;
        DecimalFormat df = new DecimalFormat("#.0");
        avg_num.setText(df.format(AVG_NUM));
    }

        public static boolean hasDuplicate(String[] arr) {
            HashSet<String> set = new HashSet<>();
            for (String str : arr) {
                if (!set.add(str)) {
                    return true;
                }
            }
            return false;
        }

    private void search(){
        FreeUI_EntityCallBack<BaseResponseBean<LotAndPackagingfileEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<LotAndPackagingfileEntity>>
                (new TypeToken<BaseResponseBean<LotAndPackagingfileEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotAndPackagingfileEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    entity = response.body().getResponse().getBody();
                    inputvalue(entity);
                    showToast("成功", true);
                    etLotID.requestFocus();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LotAndPackagingfileEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "失败");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("LOT_ID", getText(etLotID));
        map.addProperty("ACTION_TYPE", "QUERY");
        NetUtils.requestPostNet("IF.PDA_QUERY_LOT_PACKS", "Common", BreLanjianPasteBarCodeWGOutPutActivity.this, map, callBack);
    }

    private void  inputvalue(LotAndPackagingfileEntity entity){

        WO_ID = entity.getLOT().getWOID();
        MAIN_QTY = Integer.parseInt(entity.getLOT().getMAINQTY());
        BASE_REEL_NUM = Integer.parseInt(entity.getPACKS().getReelNum());
        REEL_NUM = (int)  Math.ceil(MAIN_QTY * 1.0 / BASE_REEL_NUM);
        BASE_BOX_NUM = Integer.parseInt(entity.getPACKS().getBoxNum());
        BOX_NUM = (int)  Math.ceil(MAIN_QTY * 1.0 / BASE_BOX_NUM);
        BAR_CODE_NUM = REEL_NUM + BOX_NUM;

        etLotID.setText(entity.getLOT().getLOTID());
        xinghao.setText(entity.getLOT().getUDF().getProductModel());
        fengzuang.setText(entity.getLOT().getMAINMATTYPE());
        custcode.setText(entity.getLOT().getCUSTOMERCODE());
        shuliang.setText(String.valueOf(MAIN_QTY));
        base_reel_num.setText(String.valueOf(BASE_REEL_NUM));
        base_box_num.setText(String.valueOf(BASE_BOX_NUM));
        reel_num.setText(String.valueOf(REEL_NUM));
        box_num.setText(String.valueOf(BOX_NUM));
    }

    private void btnClean1(){
        etLotID.setText(null);
        xinghao.setText(null);
        fengzuang.setText(null);
        shuliang.setText(null);
        base_reel_num.setText(null);
        base_box_num.setText(null);
        reel_num.setText(null);
        box_num.setText(null);
        avg_num.setText(null);
        bar_code_num.setText(null);
        custcode.setText(null);
        man.setText(null);
        showMans="";
        BAR_CODE_NUM=0;
        AVG_NUM=0.0;
        tvBCOPType.setText("");
        etLotID.requestFocus();
    }

    private void submit(){

        if(getText(etLotID).equals("")){
            showToast("请先扫描批次信息", false);
            return;
        }
        if(getText(man).equals("")){
            showToast("请填写操作工", false);
            return;
        }
        if(getText(bar_code_num).equals("") || getText(avg_num).equals("")){
            showToast("请点击计算产量", false);
            return;
        }
        if(getText(bar_code_num).equals("0") || getText(avg_num).equals("0.0")){
            showToast("标签数或者平均数不能为0！", false);
            return;
        }
        if(tvBCOPType.getText().toString().equals("")){
            showToast("请选择点数设备！", false);
            return;
        }


        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showToast("成功", true);
                    btnClean1();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "aaaaaaaaaaa");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("WO_ID", WO_ID);
        map.addProperty("LOT_ID", getText(etLotID));
        map.addProperty("MAIN_QTY", MAIN_QTY);
        map.addProperty("PRODUCT_MODEL", xinghao.getText().toString().trim());
        map.addProperty("MAIN_MAT_TYPE", fengzuang.getText().toString().trim());
        map.addProperty("CUSTOMER_CODE", custcode.getText().toString().trim());
        map.addProperty("TYPE", tvBCOPType.getText().toString());
        map.addProperty("MANS", man.getText().toString().trim());
        map.addProperty("MAN_NUM", MAN_NUM);
        map.addProperty("BASE_REEL_NUM", BASE_REEL_NUM);
        map.addProperty("BASE_BOX_NUM", BASE_BOX_NUM);
        map.addProperty("REEL_NUM", REEL_NUM);
        map.addProperty("BOX_NUM", BOX_NUM);
        map.addProperty("BAR_CODE_NUM", BAR_CODE_NUM);
        map.addProperty("AVG_NUM", AVG_NUM);   //double
        NetUtils.requestPostNet("IF.PDA_WG_BARCODE_OUTPUT", "Common", BreLanjianPasteBarCodeWGOutPutActivity.this, map, callBack);
        btnClean1();
    }

//    public class MTextWatcher implements TextWatcher {
//
//        @Override
//        public void onTextChanged(CharSequence s, int start, int before, int count) {
//            /**
//             * 扫描时触发 ：0,0,1
//             * 手动输入，: 012 023 034 045
//             * 手输键盘: 每个字母都会触发textWatcher事件.扫描是整体触发,不会单个触发
//             **/
//            if (start == 0 && before == 0 && count > 1) {
//
//            } else {
////               System.out.println("手动输入触发");
//            }
//        }
//
//        @Override
//        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
//
//        @Override
//        public void afterTextChanged(Editable s) { }
//    }
}